﻿using System;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.Web;

namespace TestWebApplication
{
    public abstract class Api
    {
        private const int MaxRetryCount = 1;

        protected BasicHttpBinding binding;
        protected EndpointAddress serviceAddress;
        protected X509Certificate2 certificate;

        protected CommerceAPIResponse response;
        protected Guid trackingGuid;

        public Api(BasicHttpBinding binding, EndpointAddress address, X509Certificate2 clientCert)
        {
            this.binding = binding;
            this.serviceAddress = address;
            this.certificate = clientCert;
        }

        public abstract void ExecuteCommerceApi();
        public abstract void PrepareRequestData();
        public abstract void PrepareResponseData();

        public string Execute()
        {
            this.response = new CommerceAPIResponse();
            this.trackingGuid = Guid.NewGuid();

            PrepareRequestData();

            while (!this.response.IsSuccess && this.response.NeedRetry && this.response.RetryCount < MaxRetryCount )
            {
                ExecuteCommerceApi();
            }

            if (this.response.IsSuccess)
            {
                PrepareResponseData();
            }

            return null;
        }
    }
}
